<template>
    <div class="maindivcontainer">
    <div class="container">
        <div class="qu-wrap">
            <header>
                <span @click="iterator = backBtn(), iterator.next()">&lt; 返回</span>
                <p>{{ quData.name }}</p>
            </header>
            <div class="qu-content">
                <section class="qu-item" v-for="(item, index) in questions">
                    <h3>{{ `Q${index + 1}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;${item.description}` }}
                        <span v-if="item.isMandatory === 1"> *</span>
                    </h3>
                    <textarea rows="8"
                              cols="80"
                              v-if="item.type === 'textarea'"
                              v-model="item.answer"
                              :required="item.isMandatory === 1"
                              >
					</textarea>
                    <ul v-else class="options-list">
                        <li v-for="(option, optIndex) in item.choices">
                            <label >
                                <input v-if="item.type === 'radio'"
                                       :type="item.type"
                                       :name="index + 1"
                                       @change="item.answer = optIndex">
                                <input v-else
                                       :type="item.type"
                                       :name="index + 1"
                                       @change="checkboxAnswer($event, optIndex, item.answer)">
                                <span>{{ option.description }}</span>
                            </label>
                        </li>
                    </ul>
                </section>
            </div>
            <footer>
                <span id="submitBtn" @click="iterator = submitBtn(), iterator.next()">提交问卷</span>
            </footer>
        </div>
        <div class="overlay" v-show="isShowPrompt">
            <div class="prompt-box">
                <header>
                    <span>提示</span>
                    <a href="javascript:;" @click="isShowPrompt = false">&times;</a>
                </header>
                <p>{{ promptText }}</p>
                <footer>
                    <span @click="isShowPrompt = false, iterator && iterator.next()">确定</span>
                    <span @click="isShowPrompt = false">取消</span>
                </footer>
            </div>
        </div>
    </div>
    </div>
</template>

<script>
    import Store from '../store.js';

    export default {
        name: 'Fill',
        data() {
            return {
                quData: {},
                questions: [],
                answers: {},
                promptText: '',
                isShowPrompt: false,
                selectquestionnaireId: this.$route.params.id,
                sendAnswers: [],
                fillId: sessionStorage.getItem("id"),
                sendAnswersArray: {},
                answerQuestionnaire: null
            }
        },

        beforeRouterEnter(to, from, next) {
            let id = to.params.id;
            let item = {};
            if (id !== 0) {
                let length = Store.fetch().length;
                if (id < 0 || id > length) {
                    alert('非法路由');
                    next('');
                }
                else {
                    item = Store.fetch()[id - 1];
                }

                if (item.state === 0) {
                    next();
                }
                else {
                    alert('非法路由');
                    next('/');
                }
            }
            else {
                next();
            }
        },

        created() {
            this.getData();
            this.getAnswerQuestionnaire();

        },

        methods: {

            getAnswerQuestionnaire(){
                const _this = this;
                this.axios.get("http://localhost:8088/returnAnswer/"+_this.selectquestionnaireId
                    +"/"+sessionStorage.getItem("id")).then(function (resp) {
                    if(resp.data != null) {
                        _this.answerQuestionnaire = resp.data;
                        for(let i = 0; i < _this.questions.length; i++){
                            if(_this.questions.get(i).type === "radio"){
                                _this.questions.get(i).answer = _this.answerQuestionnaire.resultChoice;
                            }else if(_this.questions.get(i).type === "textarea"){
                                _this.questions.get(i).answer = _this.answerQuestionnaire.resultString;
                            }else{
                                _this.questions.get(i).answer = _this.answerQuestionnaire.resultChoice;
                            }
                        }
                    }else{
                        _this.answerQuestionnaire = null;
                    }
                    console.log("_this.answerQuestionnaire");
                    console.log(_this.answerQuestionnaire);
                })
            },

            getData() {
                const _this = this;
                this.axios.get("http://localhost:8088/questionnaire/"+_this.selectquestionnaireId).then(function (resp) {
                    _this.quData = resp.data;
                    _this.questions = _this.quData.questions;
                    console.log("_this.quData");
                    console.log(_this.quData);
                    console.log("_this.questions");
                    console.log(_this.questions);
                    if(!_this.questions) return;
                    _this.questions.forEach((item) => {
                        if (item.type === 'checkbox') {
                            item.answer = [];
                        }
                        else if(item.type === 'radio'){
                            item.answer = '';
                        }else {
                            item.answer = '';
                        }
                    });

                })
            },

            showPrompt(text) {
                this.promptText = text;
                this.isShowPrompt = true;
            },

            checkboxAnswer(event, index, answer) {
                if (event.target.checked) {
                    answer.push(index);
                }
                else {
                    answer.splice(answer.indexOf(index), 1);
                }
            },

            requireValidate() {
                let textareas = document.querySelectorAll('textarea');
                return [].every.call(textareas, item => {
                    if (item.hasAttribute('required') && item.value.trim() === '') {
                        return false;
                    }
                    return true;
                })
            },

            getAnswer() {
                this.questions.forEach((item, index) => {
                    this.answers[`Q${index + 1}answer`] = item.answer;
                })
            },

            sendAnswer() {
                this.getAnswer();
                this.$router.push({path: '/'});
                this.questions.forEach((item) => {
                    let sendTAnswer = {};
                    if (item.type === 'checkbox') {
                        sendTAnswer.questionId = item.id;
                        sendTAnswer.resultChoice = item.answer;
                        sendTAnswer.resultString = null;
                        sendTAnswer.fillId = this.fillId;
                        sendTAnswer.questionnaireId = this.selectquestionnaireId;
                        sendTAnswer.type = "checkbox";
                    }
                    else if(item.type === 'radio'){
                        sendTAnswer.questionId = item.id;
                        sendTAnswer.resultChoice = item.answer;
                        sendTAnswer.resultString = null;
                        sendTAnswer.fillId = this.fillId;
                        sendTAnswer.questionnaireId = this.selectquestionnaireId;
                        sendTAnswer.type = "radio";
                    }else {
                        sendTAnswer.questionId = item.id;
                        sendTAnswer.resultChoice = null;
                        sendTAnswer.resultString = item.answer;
                        sendTAnswer.fillId = this.fillId;
                        sendTAnswer.questionnaireId = this.selectquestionnaireId;
                        sendTAnswer.type = "textarea";
                    }
                    this.sendAnswers.push(sendTAnswer);
                    this.sendAnswersArray.answerArray = this.sendAnswers;

                });
                this.sendTAnswers(this.sendAnswersArray);
            },

            sendTAnswers(sendAnswersArray){
                this.axios({
                    url: "http://localhost:8088/saveResult",
                    headers: {
                        'Content-Type': 'application/json;charset=utf-8'
                    },
                    method: "post",
                    params: {
                        'sendAnswersArray': encodeURI(JSON.stringify(sendAnswersArray))
                    }
                }).then({})
            },

            finishCountAdd(id){
              this.axios({
                  url: "http://localhost:8088/finishCountUp",
                  headers: {
                      'Content-Type': 'application/json;charset=utf-8'
                  },
                  method: "post",
                  params: {
                      'id': encodeURI(JSON.stringify(id))
                  }
              })  .then({})
            },

            *submitBtn() {
                let text = ``;
                if (this.quData.publishState === 0) {
                    var r = confirm("问卷尚未发布，无法提交！");
                    if (r == true) {
                        return;
                    } else {
                        return;
                    }
                    this.iterator = null;
                }
                else if (!this.requireValidate()) {
                    var r = confirm("有必填项未填写，无法提交！");
                    if (r == true) {
                        return;
                    } else {
                        return;
                    }
                    this.iterator = null;
                }
                else {
                    var r = confirm("确认提交问卷吗？");
                    if (r == true) {
                        this.answerQuestionnaire = null;
                        this.$router.push({name: 'Index'});
                    } else {
                        return;
                    }
                }
                this.finishCountAdd(this.quData.id);
                yield this.sendAnswer();
            },

            *backBtn() {
                yield this.showPrompt(`放弃答题回到主页吗？`);
                this.answerQuestionnaire = null;
                yield this.$router.push({path: '/index'});
            },
        },
    }
</script>

<style scoped lang="scss">
    @import '../style/_Fill.scss';
</style>
